package com.qi.xiaogangzai.pccache.imgloader;

import android.content.Context;
import android.widget.ImageView;

import com.qi.xiaogangzai.pccache.bean.ImageBean;
import com.qi.xiaogangzai.pccache.creator.RequestCreator;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by xioogangzai on 2017/10/31.
 * http://blog.csdn.net/qq_30379689/article/details/77349786设计模式讲解
 */

public class RxImageLoader {
    static RxImageLoader singleton;
    String mUrl;
    private RequestCreator mRequestCreator;

    //为了单例模式，修改私有的构造方法，避免被直接new出来
    private RxImageLoader(Builder builder) {
        mRequestCreator = new RequestCreator(builder.mContext);
    }

    public static RxImageLoader with(Context context) {
        if (singleton == null) {
            synchronized (RxImageLoader.class) {
                if (singleton == null) {
                    singleton = new Builder(context).build();
                }
            }
        }
        return singleton;
    }

    public RxImageLoader load(String url) {
        this.mUrl = url;
        return singleton;
    }

    //最后显示图片的方法，也就是从内存取，从文件取还是从网络取RxJava
    public void into(final ImageView imageView) {
        Observable.concat(mRequestCreator.getImageFromMemory(mUrl),
                mRequestCreator.getImageFromDisk(mUrl),
                mRequestCreator.getImageFromNetwork(mUrl))

                .subscribe(new Observer<ImageBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ImageBean imageBean) {
                        imageView.setImageBitmap(imageBean.getBitmap());
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public static class Builder {
        private Context mContext;

        public Builder(Context context) {
            this.mContext = context;
        }

        private RxImageLoader build() {
            return new RxImageLoader(this);
        }
    }


}
